var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
var app = express();
// 引入数据库处理模块
var mongoose = require('mongoose');

// 引入swagger 参数
var expressSwagger = require('express-swagger-generator')(app);
var swaggerOptions = require('./config/swagger');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

// 指定跨域
const corsOptions = {
  origin: 'http://192.168.1.20:3000',
  optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
// app.use(cors(corsOptions));

//一些中间件
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
  extended: false
}));
app.use(cookieParser());
// 导出静态路径
app.use(express.static(path.join(__dirname, 'public')));
app.use('/public', express.static(path.join(__dirname, 'public')));
app.use('/bootstrap', express.static('./node_modules/bootstrap/dist'))
app.use('/font-awesome', express.static('./node_modules/font-awesome'))
app.use('/jquery', express.static('./node_modules/jquery/dist'))

app.use(cors()); //跨域
app.disable('etag'); //禁止304缓存

// 数据库连接
mongoose.connect('mongodb://192.168.1.66:27017/test-mongo', {
  useNewUrlParser: true,
  useUnifiedTopology: true
}).then(() => console.log('数据库连接成功'))
  .catch(() => console.log('数据库连接失败'));

// 断开连接
mongoose.connection.on('disconnected', () => {
  console.log("disconnected")
});

// 路由
require('./routes')(app);
// swagger
expressSwagger(swaggerOptions);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  // res.render('error');
  res.json({
    status: res.statusCode,
    msg: err.message,
    data: {}
  })
  // next();
});

module.exports = app;
